<template>
  <!-- 设备状态 -->
  <echartsChart
    ref="deviceStatisticsRef"
    :dark="dark"
    :arrow="arrow"
    :title="title"
    :options="deviceStatisticsOptions"
    :titleBgWidth="150"
    @btn-click="toPage"
  />
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useLabelLayoutBarChartFn, useGetBarChartsAgOptions_new } from "@/hooks/useEcharts";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import { useRouter } from "vue-router";
import { queryDeviceStatistics } from "@/api/modules/operation";
import { deviceStatus_ele } from "@/utils/constant";

interface Props {
  classCode: string;
  dark?: boolean;
  arrow?: boolean;
  title?: string;
}

const props = withDefaults(defineProps<Props>(), { dark: false, arrow: false, title: "设备状态" });
const router = useRouter();
// 数据  设备状态 + 今日任务
const deviceStatisticsQueryData = ref<any>(null);
const valueIsEmpty = value => {
  if (value === "" || value == null || typeof value == "undefined") {
    return true;
  }
  return false;
};
// 设备状态
const deviceStatisticsRef = ref<InstanceType<typeof echartsChart> | null>(null);
const deviceStatisticsOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const deviceStatisticsInit = async () => {
  if (!deviceStatisticsQueryData.value?.deviceStatusStat) return;

  const ec = await deviceStatisticsRef.value.getEcharts();

  const data: any = Object.values(deviceStatisticsQueryData.value?.deviceStatusStat).map(value => {
    return valueIsEmpty(value) ? "-" : value;
  });
  const unit = "台";
  const xAxisData = Object.keys(deviceStatisticsQueryData.value?.deviceStatusStat);
  const colorList = xAxisData.map(item => deviceStatus_ele[item]?.color || "");
  const ag = useGetBarChartsAgOptions_new(xAxisData, data, false, unit, colorList, 22);
  deviceStatisticsOptions.value = useLabelLayoutBarChartFn(ec, xAxisData, data, props.title, unit, colorList, true, "top", ag);
  if (!props.dark) {
    ec?.getInstance()?.off("click");
    ec?.getInstance()?.on("click", params => {
      const query = { className: props.classCode, eqpRunStatusName: params.name };
      const path = "/all/equip/runManage/status";
      router.push({ path, query });
    });
  }
};

const toPage = () => {
  let path = "/all/equip/runManage/status"; // 设备运行台账
  let query: any = { className: props.classCode };
  router.push({ path, query });
};
// 获取数据  设备状态
const queryDeviceStatisticsFn = () => {
  const params = { classCode: props.classCode };
  queryDeviceStatistics(params).then(async res => {
    if (res) {
      deviceStatisticsQueryData.value = res;
      await deviceStatisticsInit();
    }
  });
};
onMounted(async () => {
  // 设备状态
  queryDeviceStatisticsFn();
});
/**
 * 定时用更新数据
 */
const initAll = () => {
  deviceStatisticsOptions.value = null;
  queryDeviceStatisticsFn();
};
defineExpose({
  initAll
});
</script>
